package com.turnengine.client.common.data;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.javabi.common.io.data.DataReader;
import com.javabi.common.io.data.DataWriter;
import com.javabi.common.io.data.IDataReader;
import com.javabi.common.io.data.IDataSerializer;
import com.javabi.common.io.data.IDataWriter;
import com.javabi.common.lang.UncheckedException;

public class ByteDataSerializer<O> {

	private final IDataSerializer<O> serializer;

	public ByteDataSerializer(IDataSerializer<O> serializer) {
		if (serializer == null) {
			throw new NullPointerException("serializer");
		}
		this.serializer = serializer;
	}

	public O fromByteArray(byte[] data) {
		try {
			ByteArrayInputStream input = new ByteArrayInputStream(data);
			IDataReader reader = new DataReader(input);
			return serializer.readObject(reader);
		} catch (IOException ioe) {
			throw new UncheckedException(ioe);
		}
	}

	public byte[] toByteArray(O object) {
		try {
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			IDataWriter writer = new DataWriter(output);
			serializer.writeObject(writer, object);
			writer.flush();
			return output.toByteArray();
		} catch (IOException ioe) {
			throw new UncheckedException(ioe);
		}
	}

}
